#include<iostream>
#include"/Users/yjc/Programming/eurekas-algorithm-path/2.Linklist/Linklist.cpp"

// struct ListNode {
//     int val;
//     ListNode *next;
//     ListNode() : val(0), next(nullptr) {}
//     ListNode(int x) : val(x), next(nullptr) {}
//     ListNode(int x, ListNode *next) : val(x), next(next) {}
//  };

class Solution {
public:
    ListNode* removeElementsSelf(ListNode* head, int val) {
        ListNode t(0,head);
        ListNode* ptr=head,*preptr=&t,*headptr=head;
        int cnt=0;
        while(ptr!=NULL)
        {
            if(ptr->val==val)
            {
                preptr->next=ptr->next;
                //tempptr=ptr;
                //free(ptr);
                ptr=ptr->next;//*preptr不变，只移动ptr
                continue;
            }
            preptr=ptr;
            ptr=ptr->next;
        }
        return t.next;
    }

    ListNode* removeElements1(ListNode* head, int val)//单独处理头结点
    {
        // 删除头结点
        while (head != NULL && head->val == val) { // 注意这里不是if
            ListNode* tmp = head;
            head = head->next;
            delete tmp;
        }

        // 删除非头结点
        ListNode* cur = head;
        while (cur != NULL && cur->next!= NULL) {
            if (cur->next->val == val) {
                ListNode* tmp = cur->next;
                cur->next = cur->next->next;
                delete tmp;
            } else {
                cur = cur->next;
            }
        }
        return head;
    }

    ListNode* removeElements2(ListNode* head, int val) {
        ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
        dummyHead->next = head; // 将虚拟头结点指向head，这样方面后面做删除操作
        ListNode* cur = dummyHead;
        while (cur->next != NULL) {
            if(cur->next->val == val) {
                ListNode* tmp = cur->next;
                cur->next = cur->next->next;
                delete tmp;
            } else {
                cur = cur->next;
            }
        }
        head = dummyHead->next;
        delete dummyHead;
        return head;
    }

};

int main()
{
    LinkList l;
    l.insert(7,0);
    l.insert(8,1);
    l.insert(9,2);
    l.insert(7,3);
    Solution s;
    l.head=s.removeElementsSelf(l.head,7);
    l.print();

}